package com.siwei.mes.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.experiment.ExperimentYearConfig;
import com.siwei.mes.entity.system.CompanyConfig;
import com.siwei.mes.entity.system.Serial;
import com.siwei.mes.enums.GenerateCodeEnum;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentYearConfigMapper;
import com.siwei.mes.mapper.system.CompanyConfigMapper;
import com.siwei.mes.mapper.system.SerialMapper;
import com.siwei.mes.service.system.CompanyConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 企业信息配置表(CompanyConfig)表服务实现类
 *
 * @author makejava
 * @since 2024-11-21 20:02:56
 */
@Slf4j
@Service
public class CompanyConfigServiceImpl implements CompanyConfigService {
    @Resource
    private CompanyConfigMapper companyConfigMapper;
    @Resource
    private SerialMapper serialMapper;
    @Resource
    private ExperimentYearConfigMapper experimentYearConfigMapper;

    @Override
    public Long create(CompanyConfig entity) {
        companyConfigMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public void update(CompanyConfig entity) {
        CompanyConfig companyConfig = companyConfigMapper.selectByPrimaryKey(entity.getId());
        assertTrue(companyConfig == null, "企业信息配置表信息不存在");
        companyConfigMapper.updateByPrimaryKeySelective(entity);
        // 定义编号类型与获取方法的映射关系
        Map<GenerateCodeEnum, Function<CompanyConfig, String>> codeToGetterMap = new HashMap<>();
        codeToGetterMap.put(GenerateCodeEnum.QUALITY_CERTIFICATE, CompanyConfig::getQualityCertificateNo);
        codeToGetterMap.put(GenerateCodeEnum.MIX_PROPORTION, CompanyConfig::getMixProportionNo);
        codeToGetterMap.put(GenerateCodeEnum.OPEN_APPRAISAL_LEDGER, CompanyConfig::getOpenAppraisalNo);
        codeToGetterMap.put(GenerateCodeEnum.KLLZ_SAMPLENO, CompanyConfig::getKllzSampleNo);
        codeToGetterMap.put(GenerateCodeEnum.KLLZ_CONSIGNID, CompanyConfig::getKllzConsignId);
        codeToGetterMap.put(GenerateCodeEnum.KLLZ_REPORTID, CompanyConfig::getKllzReportId);

        // 遍历映射关系，更新序列号
        for (Map.Entry<GenerateCodeEnum, java.util.function.Function<CompanyConfig, String>> entry : codeToGetterMap.entrySet()) {
            GenerateCodeEnum codeEnum = entry.getKey();
            Function<CompanyConfig, String> getter = entry.getValue();
            String number = getter.apply(entity);
            if (StringUtils.isNotEmpty(number)) {
                /**修改序号表信息*/
                Serial serial = serialMapper.selectBySerialNo(codeEnum.getCode());
                if (serial != null) {
                    serial.setSerialNumber(number);
                    serialMapper.updateByPrimaryKeySelective(serial);
                }
            }
        }
    }

    @Override
    public void delete(Long id) {
        CompanyConfig companyConfig = companyConfigMapper.selectByPrimaryKey(id);
        assertTrue(companyConfig == null, "企业信息配置表信息不存在");
        companyConfigMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<CompanyConfig> getPage(PageQuery<CompanyConfig, CompanyConfig> query) {
        CompanyConfig searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> companyConfigMapper.getList(searchParam));
    }

    @Override
    public CompanyConfig loadById(Long id) {
        CompanyConfig companyConfig = companyConfigMapper.loadById(id);
        /**重新给编号字段赋值**/
        // 定义编号类型与设置方法的映射关系
        Map<GenerateCodeEnum, BiConsumer<CompanyConfig, String>> codeToSetterMap = new HashMap<>();
        codeToSetterMap.put(GenerateCodeEnum.QUALITY_CERTIFICATE, CompanyConfig::setQualityCertificateNo);
        codeToSetterMap.put(GenerateCodeEnum.OPEN_APPRAISAL_LEDGER, CompanyConfig::setOpenAppraisalNo);
        codeToSetterMap.put(GenerateCodeEnum.MIX_PROPORTION, CompanyConfig::setMixProportionNo);
        codeToSetterMap.put(GenerateCodeEnum.KLLZ_SAMPLENO, CompanyConfig::setKllzSampleNo);
        codeToSetterMap.put(GenerateCodeEnum.KLLZ_CONSIGNID, CompanyConfig::setKllzConsignId);
        codeToSetterMap.put(GenerateCodeEnum.KLLZ_REPORTID, CompanyConfig::setKllzReportId);

        // 遍历映射关系，更新编号字段
        for (Map.Entry<GenerateCodeEnum, BiConsumer<CompanyConfig, String>> entry : codeToSetterMap.entrySet()) {
            GenerateCodeEnum codeEnum = entry.getKey();
            BiConsumer<CompanyConfig, String> setter = entry.getValue();

            /**赋值对应的编号*/
            Serial serial = serialMapper.selectBySerialNo(codeEnum.getCode());
            if (serial != null) {
                setter.accept(companyConfig, serial.getSerialNumber());
            }
        }
        return companyConfig;
    }

    @Override
    public List<CompanyConfig> getAll(CompanyConfig entity) {
        return companyConfigMapper.getList(entity);
    }

    @Override
    public void reduceReportId(Long experimentId, String testCode) {
        log.info("开始退回对应协会编号，试验委托id：【{}】，对应试验项目code：【{}】", experimentId, testCode);
        if (experimentId == null || StringUtils.isBlank(testCode)) {
            return;
        }

        CompanyConfig companyConfig = companyConfigMapper.loadById(1L);
        if (companyConfig == null) {
            log.info("企业设置为空，直接跳过！");
            return;
        }

        ExperimentYearConfig yearConfig = experimentYearConfigMapper.selectByExperimentId(experimentId);
        if (yearConfig == null) {
            return;
        }
        if (!yearConfig.getTestCode().equals(testCode)) {
            return;
        }
        /**修改对应报告编号的数据减少一*/
        TestProjectEnum testProjectEnum = TestProjectEnum.getName(testCode);
        if (testProjectEnum == null) {
            log.info("试验项目配置为空直接跳过");
            return;
        }
        switch (testProjectEnum) {
            case CONCRETE_PARAM_XNBG_LLZHL:
                companyConfig.setKllzSampleNo(this.reduceSerialNumber(GenerateCodeEnum.KLLZ_SAMPLENO, "%05d"));
                companyConfig.setKllzReportId(this.reduceSerialNumber(GenerateCodeEnum.KLLZ_REPORTID, "%06d"));
                companyConfig.setKllzConsignId(this.reduceSerialNumber(GenerateCodeEnum.KLLZ_CONSIGNID, "%06d"));
                companyConfigMapper.updateByPrimaryKeySelective(companyConfig);
                break;
            default:
                log.info("未知试验项目类型：" + testCode);
        }
    }

    /**
     * 修改编号数据
     *
     * @param generateCodeEnum 编号类型
     * @param format           几位数
     */
    public String reduceSerialNumber(GenerateCodeEnum generateCodeEnum, String format) {
        try {
            Serial serial = serialMapper.selectBySerialNo(generateCodeEnum.getCode());
            if (serial == null || StringUtils.isBlank(serial.getSerialNo())) {
                return null;
            }
            String serialNumber = serial.getSerialNumber();
            int num = Integer.parseInt(serialNumber);
            num--;
            String serialNumberNew = String.format(format, num);
            serial.setSerialNumber(serialNumberNew);
            return serialNumberNew;
        } catch (Exception e) {
            log.info("修改编号失败，错误信息：【{}】", e.getMessage(), e);
            return null;
        }
    }
}
